//
//  AppDelegate.m
//  Yueshi
//
//  Created by Northwan on 15/6/28.
//  Copyright (c) 2015年 悦食中国. All rights reserved.
//

#import "AppDelegate.h"
#import "CustomTabBarCtrl.h"
#import "WeiboSDK.h"
#import "SinaDataTool.h"
#import "WeChatUserinfoRes.h"
#import "WeChatUtil.h"
#import "BPush.h"
#include <TencentOpenAPI/TencentOAuth.h>
#include <BaiduMapAPI/BMapKit.h>
#import "WXApi.h"
#import <AlipaySDK/AlipaySDK.h>
#import "YSSplashAdCtrl.h"
#import "YSPushModel.h"
#import "AFNetworkActivityIndicatorManager.h"

@interface AppDelegate ()<WeiboSDKDelegate,WXApiDelegate>
@property (assign, nonatomic) WXScene scene;
@property (strong, nonatomic) BMKMapManager *mapManager;
@end

@implementation AppDelegate

- (id)init{
    if(self = [super init]){
        _scene = WXSceneSession;
    }
    return self;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //计算缩放比值
    if(SCREENH > 480){
        self.autoSizeScaleX = SCREENW/320;
        self.autoSizeScaleY = SCREENH/568;
    }else{
        self.autoSizeScaleX = 1.0;
        self.autoSizeScaleY = SCREENH/568;
    }
    
    //设置整体的导航栏的背影颜色
    [[UINavigationBar appearance] setBarTintColor:PUBLIC_BG];

    if (iOS8) {
        [[UINavigationBar appearance] setTranslucent:NO];
    }
    //设置状态栏的文字颜色(前提得到Info.plist中设置UIViewControllerBasedStatusBarAppearance为NO)
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.rootViewController = [[YSSplashAdCtrl alloc]init];
    [self.window makeKeyAndVisible];
    
    //初始化新浪微博
    [self initSinaWeibo];
    //微信相关
    [WXApi registerApp:kWxAppId withDescription:@"yueshiweixinpay"];
    //百度定位
    [self initBaiduMapLocation];
    //百度push
    [self initBaiduPushWithOptions:launchOptions];
    
#ifdef DEBUG  //talking data crash exception：debug close，online open
    [TalkingData setExceptionReportEnabled:NO];
#else
    [TalkingData setExceptionReportEnabled:YES];
#endif

    //talking data
    [TalkingData sessionStarted:kTDAppId
                  withChannelId:kChannel];
    return YES;
}

-(void)initSinaWeibo{
    [WeiboSDK registerApp:kSinaAppKey];
    [WeiboSDK enableDebugMode:YES];
}

-(void)initBaiduMapLocation{
    _mapManager = [[BMKMapManager alloc]init];
    // 如果要关注网络及授权验证事件，请设定 generalDelegate参数
    BOOL ret = [_mapManager start:kBaiduLocationAppKey  generalDelegate:nil];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
}

- (void)initBaiduPushWithOptions:(NSDictionary *)launchOptions{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType myTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:myTypes categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }else {
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }
    
#warning 测试 开发环境 时需要修改BPushMode为BPushModeDevelopment 生产环境为BPushModeProduction
    // 在 App 启动时注册百度云推送服务
    [BPush registerChannel:launchOptions apiKey:kBaiduPushAppkey pushMode:BPushModeDevelopment withFirstAction:nil withSecondAction:nil withCategory:nil isDebug:YES];
    // App 是用户点击推送消息启动
    NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (userInfo) {
        NSLog(@"从消息启动:%@",userInfo);
        [BPush handleNotification:userInfo];
        [DefaultsHelper setObject:userInfo forKey:kRemotePushNortif];
    }
    //角标清0
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    //测试本地通知
    //[self performSelector:@selector(pushLocalNotifi) withObject:nil afterDelay:1.0];
    
}

- (void)pushLocalNotifi
{
    NSLog(@"测试本地通知");
    NSDate *fireDate = [[NSDate new] dateByAddingTimeInterval:5];
    [BPush localNotification:fireDate alertBody:@"这是本地通知" badge:3 withFirstAction:@"打开" withSecondAction:@"关闭" userInfo:nil soundName:nil region:nil regionTriggersOnce:YES category:nil];
}

// 在 iOS8 系统中，还需要添加这个方法。通过新的 API 注册推送服务
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    [application registerForRemoteNotifications];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [BPush registerDeviceToken:deviceToken];
    
    NSString *deviceTokenStr = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                                 stringByReplacingOccurrencesOfString: @">" withString: @""]
                                stringByReplacingOccurrencesOfString: @" " withString: @""];
    NSLog(@"deviceToken-------%@",deviceTokenStr);
   [DefaultsHelper setObject:deviceTokenStr forKey:kDeviceToken];
   [BPush bindChannelWithCompleteHandler:^(id result, NSError *error){
        NSLog(@"[BPush getChannelId]------:%@",[BPush getChannelId]);
        [DefaultsHelper setObject:[BPush getChannelId] forKey:kChannelId];
   }];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"DeviceToken 获取失败，原因：%@",error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    completionHandler(UIBackgroundFetchResultNewData);
    NSLog(@"iOS7.0之后   推送内容：%@",userInfo);
    
    //isEnterForeground==true的话，这个代表是app在后台运行，用户点击了推送消息，进行相关处理
    [[NSNotificationCenter defaultCenter] postNotificationName:kRemotePushNortif object:[NSNumber numberWithBool:_isEnterForeground] userInfo:userInfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    // App 收到推送通知
    [BPush handleNotification:userInfo];
    NSLog(@"推送内容：%@",userInfo);
    //isEnterForeground==true的话，这个代表是app在后台运行，用户点击了推送消息，进行相关处理
    [[NSNotificationCenter defaultCenter] postNotificationName:kRemotePushNortif object:[NSNumber numberWithBool:_isEnterForeground] userInfo:userInfo];
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
     NSLog(@"接收到本地通知");
    [BPush showLocalNotificationAtFront:notification identifierKey:nil];
}

-(void)didReceiveWeiboRequest:(WBBaseRequest *)request{
    NSLog(@"appdelegate-----didReceiveWeiboRequest:%@",request);
}

-(void)didReceiveWeiboResponse:(WBBaseResponse *)response{
    if([response statusCode]==WeiboSDKResponseStatusCodeSuccess){
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        if([response isKindOfClass:[WBAuthorizeResponse class]]){
            NSString *uid =  [(WBAuthorizeResponse *)response userID];
            NSString *token = [(WBAuthorizeResponse *)response accessToken];
            [params setObject:uid forKey:@"uid"];
            [params setObject:token forKey:@"access_token"];
            [SinaDataTool getUserinfo:params success:^(SinaUserInfoRes *result) {
                if(result){
                    WeChatUserinfoRes *userResult = [[WeChatUserinfoRes alloc]init];
                    [userResult setUnionid:[NSString stringWithFormat:@"%ld",(long)result.id]];
                    [userResult setNickname:result.screen_name];
                    [userResult setClientType:@"2"];
                    [userResult setHeadimgurl:result.profile_image_url];
                    NSLog(@"%@",result.gender);
                    [[NSNotificationCenter defaultCenter]postNotificationName:kOauthLoginNortif object:userResult];
                }
                NSLog(@"微博调用的返回用户信息%@",result);
            } failure:^(NSError *error) {
                ShowTips(@"获取微博用户信息失败");
            }];
        }
        }else if([response statusCode]==WeiboSDKResponseStatusCodeUserCancel){
        ShowTips(@"用户取消授权");
    }else{
        ShowTips(@"授权登录失败");
    }
    NSLog(@"appdelegate-----didReceiveWeiboResponse:%@",response);
}

-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    //-----------alipay start-------------
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            [self sendPayNotifyStatus:resultDic[@"resultStatus"]]; ;
            NSLog(@"result = %@   resultStatus =  %@",resultDic,resultDic[@"resultStatus"]);
        }];
    }
    if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回 authCode
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
    }
    //-----------alipay end-------------
    if([url.absoluteString hasPrefix:@"wb"]) {
        return [WeiboSDK handleOpenURL:url delegate:self];
    }else if([url.absoluteString hasPrefix:@"tencent"]){
        return [TencentOAuth HandleOpenURL:url];
    }else if ([url.absoluteString hasPrefix:@"yueshiopen://virtual?"]){//浏览器打开app
         NSString *newUrl = [self decodeFromPercentEscapeString:[url absoluteString]];
        if(_isEnterForeground){//前台
            [[NSNotificationCenter defaultCenter]postNotificationName:kToOtherPageNortif object:newUrl];
        }else{//后台
            YSPushModel *userInfo = [YSPushModel new];
            [userInfo setValue:@[newUrl]];
            [userInfo setMessageType:PushMessageVirtualProtocolType];
            [DefaultsHelper setObject:[userInfo keyValues] forKey:kRemotePushNortif];
        }
        return YES;
    }
    
    NSLog(@"%@",url.resourceSpecifier);
    return [WXApi handleOpenURL:url delegate:self];;
}

-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    if ([url.absoluteString hasPrefix:@"wb"]) {
        return [WeiboSDK handleOpenURL:url delegate:self];
    }else if([url.absoluteString hasPrefix:@"tencent"]){
        return [TencentOAuth HandleOpenURL:url];
    }
    return [WXApi handleOpenURL:url delegate:self];;
}

- (NSString *)decodeFromPercentEscapeString: (NSString *) input
{
    NSMutableString *outputStr = [NSMutableString stringWithString:input];
    [outputStr replaceOccurrencesOfString:@"+"
                               withString:@" "
                                  options:NSLiteralSearch
                                    range:NSMakeRange(0, [outputStr length])];
    
    return [outputStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

-(void) onReq:(BaseReq*)req{
    NSLog(@"%@",req);
}

-(void) onResp:(BaseResp *)mResp{//wx response
    if([mResp isKindOfClass:[SendMessageToWXResp class]]){//wx share response
        switch (mResp.errCode) {
            case WXSuccess:
                
                ShowTips(@"发送成功")
                break;
            case WXErrCodeUserCancel:
                ShowTips(@"取消发送")
                break;
            case WXErrCodeSentFail:
                ShowTips(@"发送失败")
                break;
            case WXErrCodeAuthDeny:
                ShowTips(@"授权失败")
                break;
            default:
                
                break;
        }
    }else if([mResp isKindOfClass:[PayResp class]]){//wx pay response
        switch (mResp.errCode) {
            case WXSuccess:
                NSLog(@"支付成功");
                [self sendPayNotifyStatus:@"9000"];
                break;
            case WXErrCodeUserCancel:
                NSLog(@"用户取消支付");
                [self sendPayNotifyStatus:@"6001"];
                break;
            default:
                NSLog(@"支付失败");
                [self sendPayNotifyStatus:@"4000"];
                break;
        }
    }else if([mResp isKindOfClass:[SendAuthResp class]]){
        switch (mResp.errCode) {
            case WXSuccess:
                NSLog(@"登录授权成功");
                [WeChatUtil getWxResqParams:mResp];
                break;
            case WXErrCodeUserCancel:
                NSLog(@"用户取消授权");
                ShowTips(@"用户取消授权")
                break;
            case WXErrCodeAuthDeny:
                NSLog(@"授权失败");
                break;
            default:
                
                break;
        }
    }
}

/**
 *  发送支付结果通知
 *
 *  @param resultCode
 */
-(void)sendPayNotifyStatus:(NSString *)resultCode{
    [[NSNotificationCenter defaultCenter] postNotificationName:kPayResultStatusNortif object:resultCode];
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    _isEnterForeground = YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    _isEnterForeground = NO;
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
